<script setup lang="ts">
import { ref, reactive } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { collectionUpdate, collectionInfo, getAccessToken, getCardInfo, getCardAdd, getCardEdit, getOcrCard } from "@/apis/my";
import { uploadImg } from "@/utils/request";
import { toast, checkPhon, checkBankCard } from "@/utils/tools";

const accessToken = ref()
let state = reactive({
  introducerName: "", //姓名
  introducerTel: "", //联系方式
  bankCardNumber: "", //银行款号
  carBlank: "", //开户行
  cardImage1: "", //身份证正面照片路径
  cardImage2: "", //身份证反面照片路径
  businessLicense: "", //营业执照
  bankCardImage1: "", //银行卡号正面照片路径
  bankCardImage2: "", //银行卡号反面照片路径
  name: "",
  addr: "",
  gender: "",
  nationality: "",
  id: "",
  validDate: "",
  phone: "",
  birth: "",
  type: "",
  state: null,
  remark: "",
  carId: ""
});
const idcardYes = ref(false)
const cardRzShow = ref('')
const loading = ref(false)
const disabledSave = ref(false)
const disabledBank = ref(false)
let cardImageNum = ref('')
// 收款信息  查询
const getCollectionInfo = async () => {
  let { data = {}, code } = await collectionInfo();
  if (code == "200") {
    state.introducerName = data.introducerName ?? ""; //姓名
    state.introducerTel = data.introducerTel ?? ""; //联系方式
    state.bankCardNumber = data.bankCardNumber ?? ""; //银行款号
    state.carBlank = data.carBlank ?? ""; //开户行
    state.cardImage1 = data.cardImage1 ?? ""; //身份证正面照路径
    state.cardImage2 = data.cardImage2 ?? ""; //身份证反面照片路径
    state.businessLicense = data.businessLicense ?? ""; //营业执照
    state.bankCardImage1 = data.bankCardImage1 ?? ""; //银行卡号正面照片路径
    state.bankCardImage2 = data.bankCardImage2 ?? ""; //银行卡号反面照片路径
  }
};

// 收款信息  查询
const getCollectionUpdate = async () => {
  let params = {
    introducerName: state.introducerName, //姓名
    introducerTel: state.introducerTel, //联系方式
    bankCardNumber: state.bankCardNumber.replace(/\s*/g, ""), //银行款号
    carBlank: state.carBlank, //开户行
    cardImage1: state.cardImage1, //身份证正面照片路径
    cardImage2: state.cardImage2, //身份证反面照片路径
    businessLicense: state.businessLicense, //营业执照
    bankCardImage1: state.bankCardImage1, //银行卡号正面照片路径
    bankCardImage2: state.bankCardImage2, //银行卡号反面照片路径
  };
  let { rows, code, msg } = await collectionUpdate(params);
  // toast(msg);
  if (code == "200") {
    setTimeout(function () {
      uni.navigateBack();
    }, 1500);
  }
};

const handleUploadImage = (type: any) => {
  // let files = e.file;
  cardImageNum.value = type
  uni.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: (imgRes: any) => {
      let files = imgRes.tempFiles;
      files.forEach(async (item: any, index: number) => {
        // #ifdef  MP-WEIXIN
        let resUpload: any = await uploadImg(item.path);
        // #endif
        // #ifdef WEB
        let resUpload: any = await uploadImg(item);
        // #endif
        if (type == "cardImage1") {
          state.type = "Front"
          state.cardImage1 = resUpload.data.url;
          // #ifdef  MP-WEIXIN
          getAccessTokenFn()
          // #endif
        } else if (type == "cardImage2") {
          state.cardImage2 = resUpload.data.url;
          state.type = "Back"
          // #ifdef  MP-WEIXIN
          getAccessTokenFn()
          // #endif
        } else if (type == "bankCardImage1") {
          state.bankCardImage1 = resUpload.data.url;
        } else if (type == "bankCardImage2") {
          state.bankCardImage2 = resUpload.data.url;
        } else if (type == "businessLicense") {
          state.businessLicense = resUpload.data.url;
        }
      });
    },
  });
};
const getAccessTokenFn = async () => {
  let res = await getAccessToken()
  accessToken.value = res.data.accessToken
  await getidCardOCRFn()
}
// getOcrCard
const getidCardOCRFn = async () => {
  let params = {
    access_token: accessToken.value,
    type: state.type, //'Front' 正面
    img_url: state.type === 'Front' ? state.cardImage1 : state.cardImage2
  }
  let res = await getOcrCard(params)
  if (res.data.errcode === 0) {
    idcardYes.value = false
    state.type = res.data.type
    if (state.cardImage1 != "" && res.data.type === 'Front' && cardImageNum.value == 'cardImage1') {
      state.name = res.data.name
      state.addr = res.data.addr
      state.gender = res.data.gender
      state.nationality = res.data.nationality
      state.carId = res.data.id
      state.birth = res.data.birth
      // disabledBank.value = false
      if (state.cardImage2 == "") {
        disabledBank.value = false
      }
      return
    }
    if (state.cardImage2 != "" && res.data.type === 'Back' && cardImageNum.value == 'cardImage2') {
      state.validDate = res.data.validDate
      disabledBank.value = true
      return
    }
    else {
      idcardYes.value = true
      toast("请上传正确的身份证照片！");
    }
  } else {
    idcardYes.value = true
    toast("请上传正确的身份证照片！");
  }
}
const getidCardOCRFn1 = async () => {
  let params = {
    access_token: accessToken.value,
    type: state.type, //'Front' 正面
    img_url: state.type === 'Front' ? state.cardImage1 : state.cardImage2
  }
  uni.request({
    url: `https://api.weixin.qq.com/cv/ocr/idcard?type=${params.type}&img_url=${params.img_url}&access_token=${params.access_token}`,
    // data: {
    //   type: 'Front',
    //   img_url: state.cardImage1,
    //   access_token: accessToken.value
    // },
    method: 'POST',
    success(res) {
      if (res.data.errcode === 0) {
        idcardYes.value = false
        state.type = res.data.type
        if (state.cardImage1 != "" && res.data.type === 'Front') {
          state.name = res.data.name
          state.addr = res.data.addr
          state.gender = res.data.gender
          state.nationality = res.data.nationality
          state.carId = res.data.id
          state.birth = res.data.birth
          if (state.cardImage2 == "") {
            disabledBank.value = false
          }
        }
        if (state.cardImage2 != "" && res.data.type === 'Back') {
          state.validDate = res.data.validityPeriod
          disabledBank.value = true
        }
        // if(res.data.type === 'Front'){
        //   state.name = res.data.name
        //   state.addr = res.data.addr
        //   state.gender = res.data.gender
        //   state.nationality = res.data.nationality
        //   state.id = res.data.id
        //   state.birth = res.data.birth
        //   state.validDate = ''
        // }else{
        //   state.validDate = res.data.validDate
        // }
      } else {
        idcardYes.value = true
        toast("请上传正确的身份证照片！");
      }
    }, fail(err) {
      toast("请上传正确的身份证照片！");
    }
  })
}
const isValidBankCardNumber = (cardNumber: any) => {
  // 去除空格和短横线
  const normalizedCardNumber = cardNumber.replace(/\s|-/g, '');

  // 正则表达式校验卡号长度和开头数字
  const cardPattern = /^(62|4\d{3}|5[1-5]\d{2}|6011|65|3[47]\d{2}|30[0123]\d|305\d)\d{12,19}$/;
  if (!cardPattern.test(normalizedCardNumber)) {
    return false;
  }

  // Luhn算法校验
  function luhnCheck(value: any) {
    let sum = 0;
    let shouldDouble = false;
    for (let i = value.length - 1; i >= 0; i--) {
      let digit: any = parseInt(value[i], 10);
      if (shouldDouble) {
        digit *= 2;
        if (digit > 9) {
          digit -= 9;
        }
      }
      sum += digit;
      shouldDouble = !shouldDouble;
    }
    return sum % 10 === 0;
  }

  return luhnCheck(normalizedCardNumber);
}
const saveClick = () => {
  // #ifdef MP-WEIXIN
  if (idcardYes.value === true) {
    // 此处是ocr校验
    toast("请上传正确的身份证照片！");
    return
  }
  // #endif
  if (!state.cardImage1) {
    toast("请上传身份证正面照片！");
    return false;
  }
  if (!state.cardImage2) {
    toast("请上传身份证反面照片！");
    return false;
  }
  // #ifdef MP-WEIXIN
  if (disabledBank.value === false) {
    // 此处是ocr校验
    toast("请上传身份证反面照片！");
    return false;
  }
  // #endif
  if (!state.name) {
    toast("请填姓名！");
    return false;
  }
  if (!state.phone) {
    toast("请填写联系方式！");
    return false;
  }
  if (!checkPhon(state.phone)) {
    toast("联系方式格式不正确！");
    return false;
  }
  if (!state.gender) {
    toast("请填写性别！");
    return false;
  }
  if (!state.addr) {
    toast("请填写地址！");
    return false;
  }
  if (!state.carId) {
    toast("请填写身份证号码！");
    return false;
  }
  if (!isValidChineseID(state.carId)) {
    toast("身份证号码格式不正确！");
    return false;
  }
  if (!state.validDate) {
    toast("请填写有效期！");
    return false;
  }
  if (!state.nationality) {
    toast("请填写民族！");
    return false;
  }
  // 此处需要校验 是否是走增加认证接口 还是修改认证接口
  if (cardRzShow.value === "addCard") {
    getCardAddFn()
  }
  if (cardRzShow.value === "editCard") {
    getCardEditFn()
  }
};
// 身份证校验
const isValidChineseID = (idCard: string): boolean => {
  const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (!idCardReg.test(idCard)) {
    return false;
  }

  // 身份证号码的每位乘以其位置的系数（18位的前17位）
  const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  // 对应的校验码字符
  const checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

  // 身份证15位转18位
  idCard = idCard.replace(/(\d{15})$/, '$119$2$3');

  // 加权求和
  let sum = 0;
  for (let i = 0; i < 17; i++) {
    sum += parseInt(idCard.charAt(i), 10) * factor[i];
  }

  // 计算校验码
  const checkDigit = checkCode[sum % 11];

  // 检查最后一位校验码是否正确
  if (idCard.charAt(17).toUpperCase() !== checkDigit) {
    return false;
  }

  // 简单的出生日期验证，不考虑非法日期如2月30日
  const birthday = idCard.substring(6, 14);
  const year = parseInt(birthday.substring(0, 4), 10);
  let month = parseInt(birthday.substring(4, 6), 10) as any
  let day = parseInt(birthday.substring(6, 8), 10) as any
  const date = new Date(year, month - 1, day);
  if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
    return false;
  }
  month = month.toString().padStart(2, '0');
  day = day.toString().padStart(2, '0');
  state.birth = `${year}-${month}-${day}`
  // 注意：这里未进行详细的地址码验证，实际应用中可能需要更详尽的地址码数据进行校验
  return true;
}

// 增加认证
const getCardAddFn = async () => {
  let params = {
    name: state.name,
    phone: state.phone,
    sex: state.gender === '男' ? '0' : '1',
    address: state.addr,
    // id: state.id,
    carId: state.carId,
    validityPeriod: state.validDate,
    nation: state.nationality,
    birth: state.birth,
    cardFront: state.cardImage1,
    cardOpposite: state.cardImage2,
  }
  loading.value = true
  disabledSave.value = true
  let res = await getCardAdd(params)
  if (res.code === 200) {
    toast(res.msg);
    setTimeout(function () {
      uni.switchTab({
        url: '/pages/my/my'
      })
    }, 1000);
    loading.value = false
    disabledSave.value = false
  } else {
    toast(res.msg);
    loading.value = false
    disabledSave.value = false
  }
}
// 修改认证
const getCardEditFn = async () => {
  let params = {
    name: state.name,
    phone: state.phone,
    sex: state.gender === '男' ? '0' : '1',
    address: state.addr,
    id: state.id,
    carId: state.carId,
    validityPeriod: state.validDate,
    nation: state.nationality,
    birth: state.birth,
    cardFront: state.cardImage1,
    cardOpposite: state.cardImage2,
  }
  loading.value = true
  disabledSave.value = true
  let res = await getCardEdit(params)
  if (res.code === 200) {
    toast(res.msg);
    uni.switchTab({
      url: '/pages/my/my'
    })
    loading.value = false
    disabledSave.value = false
  } else {
    toast(res.msg);
    loading.value = false
    disabledSave.value = false
  }
}
// 实名认证查询
const getCardInfoFn = async () => {
  let res = await getCardInfo();
  if (res.code === 500) {
    // toast(res.msg);
    cardRzShow.value = 'addCard'
  } else {
    cardRzShow.value = 'editCard'
    state.name = res.data.name
    state.phone = res.data.phone
    state.addr = res.data.address
    state.gender = res.data.sex == '0' ? '男' : '女'
    state.nationality = res.data.nation
    state.id = res.data.id
    state.carId = res.data.carId
    state.birth = res.data.birth
    state.validDate = res.data.validityPeriod
    state.state = res.data.state //0-待审核  1-审核已通过 2-审核失败
    state.cardImage1 = res.data.cardFront
    state.cardImage2 = res.data.cardOpposite
    state.remark = res.data.remark //审核失败原因
    disabledBank.value = true
  }
}
onLoad(() => {
  getCardInfoFn()
});
</script>

<template>
  <view class="margin-bt-box">
    <!-- <view class="card-box">
      <view class="inp-box flex flex-item-center">
        <view class="li-title">
          <text class="red-text">*</text>
          <text>开户名：</text>
        </view>
        <input
          type="text"
          placeholder="请输入"
          v-model="state.introducerName"
        />
      </view>
      <view class="inp-box flex flex-item-center">
        <view class="li-title">
          <text class="red-text">*</text>
          <text>联系方式：</text>
        </view>
        <input type="text" placeholder="请输入" v-model="state.introducerTel" />
      </view>
      <view class="inp-box flex flex-item-center">
        <view class="li-title">
          <text class="red-text">*</text>
          <text>银行卡号：</text>
        </view>
        <input
          type="number"
          placeholder="请输入"
          v-model="state.bankCardNumber"
        />
      </view>
      <view class="inp-box flex flex-item-center">
        <view class="li-title">
          <text class="red-text">*</text>
          <text>开户行：</text>
        </view>
        <input type="text" placeholder="请输入" v-model="state.carBlank" />
      </view>
    </view> -->
    <view class="card-box">
      <!-- <view class="inp-box flex flex-item-center">
        <view class="li-title">
          <text class="red-text">*</text>
          <text>请上传银行卡照片：</text>
        </view>
      </view> -->
      <!-- <view class="img-list flex flex-between">
        <view class="img-box" @tap="handleUploadImage('bankCardImage1')">
          <image
            src="@/static/images/identity.png"
            v-if="!state.bankCardImage1"
          />
          <text v-if="!state.bankCardImage1">银行卡正面</text>
          <image :src="state.bankCardImage1" v-else />
        </view>
        <view class="img-box" @tap="handleUploadImage('bankCardImage2')">
          <image
            src="@/static/images/identity.png"
            v-if="!state.bankCardImage2"
          />
          <text v-if="!state.bankCardImage2">银行卡反面</text>
          <image :src="state.bankCardImage2" v-else />
        </view>
      </view> -->
      <view class="inp-box flex flex-item-center">
        <view class="li-title">
          <text class="red-text">*</text>
          <text>请上传身份证照片：</text>
        </view>
      </view>
      <view class="img-list flex flex-between">
        <view class="img-box" @tap="handleUploadImage('cardImage1')">
          <image src="@/static/images/smrz.png" v-if="!state.cardImage1" />
          <!-- <text v-if="!state.cardImage1">身份证正面</text> -->
          <image :src="state.cardImage1" v-else />
        </view>
        <view class="img-box" @tap="handleUploadImage('cardImage2')">
          <image src="@/static/images/identity.png" v-if="!state.cardImage2" />
          <text v-if="!state.cardImage2">身份证反面</text>
          <image :src="state.cardImage2" v-else />
        </view>
        <!-- 认证状态 -->
        <view class="status-text">
          <view class="stateimg" v-if="state.state === 0">
            <image src="@/static/images/state0.png" />
          </view>
          <view class="stateimg" v-if="state.state === 1">
            <image src="@/static/images/state1.png" />
          </view>
          <view class="stateimg" v-if="state.state === 2">
            <image src="@/static/images/state2.png" />
          </view>
        </view>
      </view>

      <!-- 表单身份证信息 -->
      <view class="card-box">
        <view class="sfrz-name">身份证信息</view>
        <uv-line />
        <view class="inp-box flex flex-item-center">
          <view class="li-title">
            <text class="red-text">*</text>
            <text>姓名：</text>
          </view>
          <input type="text" placeholder="请输入" v-model="state.name" />
        </view>
        <view class="inp-box flex flex-item-center">
          <view class="li-title">
            <text class="red-text">*</text>
            <text>手机号：</text>
          </view>
          <input type="number" placeholder="请输入" v-model="state.phone" />
        </view>
        <view class="inp-box flex flex-item-center">
          <view class="li-title">
            <text class="red-text">*</text>
            <text>性别：</text>
          </view>
          <input type="text" placeholder="请输入" v-model="state.gender" />
        </view>
        <view class="inp-box flex flex-item-center">
          <view class="li-title">
            <text class="red-text">*</text>
            <text>民族：</text>
          </view>
          <input type="text" placeholder="请输入" v-model="state.nationality" />
        </view>
        <view class="inp-box flex flex-item-center">
          <view class="li-title">
            <text class="red-text">*</text>
            <text>身份证号：</text>
          </view>
          <input type="number" placeholder="请输入" v-model="state.carId" />
        </view>
        <view class="inp-box flex flex-item-center">
          <view class="li-title">
            <text class="red-text">*</text>
            <text>有效期：</text>
          </view>
          <input type="text" placeholder="请输入" v-model="state.validDate" />
        </view>
        <view class="inp-box flex flex-item-center">
          <view class="li-title">
            <text class="red-text">*</text>
            <text>地址：</text>
          </view>
          <input type="text" placeholder="请输入" v-model="state.addr" />
        </view>
        <view class="inp-box flex flex-item-center" v-if="state.state == 2">
          <view class="li-title">
            <text class="red-text"></text>
            <text>驳回原因：</text>
          </view>
          <input type="text" placeholder="" v-model="state.remark" :disabled="true" />
        </view>
      </view>
    </view>
    <view class="button-box" v-if="state.state == 2 || cardRzShow === 'addCard'">
      <button @tap="saveClick" :loading="loading" :disabled="disabledSave">提交</button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.card-box {
  margin-top: 26rpx;
  background-color: rgba(255, 255, 255, 1);

  .inp-box {
    padding: 30rpx;
    box-sizing: border-box;
    border-bottom: 2rpx solid rgba(239, 239, 239, 1);

    &:last-child {
      border-bottom: none;
    }

    .li-title {
      color: #101010;

      .red-text {
        margin-right: 8rpx;
        font-size: 28rpx;
        color: rgba(231, 45, 17, 1);
      }

      text {
        font-size: 28rpx;
      }
    }

    input {
      flex: 0.9;
      font-size: 28rpx;
    }
  }

  .img-list {
    padding: 15px;
    position: relative;

    .status-text {
      position: absolute;
      right: 40rpx;
      top: 0;
      z-index: 1;

      .stateimg {
        width: 120rpx;
        height: 105rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    .img-box {
      flex: 0.48;
      // width: 100%;
      position: relative;

      image {
        width: 100%;
        height: 240rpx;
        border-radius: 8px;
      }

      text {
        position: absolute;
        left: 50%;
        bottom: 10px;
        transform: translateX(-50%);
        color: rgba(16, 16, 16, 1);
        font-size: 12px;
      }
    }
  }
}

.button-box {
  position: fixed;
  bottom: 0;
  left: 50%;
  transform: translate(-50%);
  width: 100%;
  padding: 10px 15px 20px;
  box-sizing: border-box;
  background-color: #fff;
  box-shadow: 0 -4rpx 4rpx rgba(0, 0, 0, .1);
  border: 0rpx solid rgb(187, 187, 187);
  z-index: 999;

  button {
    height: 40px;
    border-radius: 40rpx;
    background: #C7452F;
    color: #fff;
    font-size: 28rpx;
    border: 0rpx solid rgb(187, 187, 187);
  }
}

.margin-bt-box {
  padding-bottom: 140px;
}

.sfrz-name {
  font-weight: 600;
  font-size: 32rpx;
  color: #222222;
  padding: 30rpx;
}
</style>
